package com.example.config;


import feign.RequestInterceptor;
import feign.RequestTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * @Classname FeignClientInterceptor
 * @Description TODO
 * @Date 2022/3/22 23:45
 * @Created by XiongXiong
 * @Author: X.I.O
 */
@Slf4j
@Component
public class FeignClientInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {
      //  requestTemplate.header("Authorization","Bearer 676e5808-6f05-4aa1-9f8a-86f39c10d45b");

        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();


        //拦截器
        //使用RequestContextHolder工具获取request相关变量

            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
//            取出request
                HttpServletRequest request = attributes.getRequest();
//                取出所有请求头
                Enumeration<String> headerNames = request.getHeaderNames();
                while (headerNames.hasMoreElements()) {
                    String name = headerNames.nextElement();   // key
                    String value = request.getHeader(name);   //value
                    requestTemplate.header(name, value);
                }
            }
    }

}
